-- NewClothesPanel

local ListViewVertical = require("app.widget.listview.ListViewVertical")
local NewClothesRender = import(".renders.NewClothesRender")

local Top_OpItemNum = 6 -- 上方可操作item个数

local ClassRef = app.mvc.createPanelClass(...)

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.NewClothesPanelNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	self._curSelectedClothesList = {} -- 当前选中的时装列表 此列表只用来存储当前页签选中的时装id而非render

	self._curSelectedIndex = 1 -- 默认选中第一项

	for i = 1, Top_OpItemNum do
		local  typeName = GD:getEquipPosName( GD:getClothesSubLocationFromID( i ) )
		local btn = self._ui["Panel/Panel_top"]:getChildByName( "Button_"..i )
		self._ui["Panel/Panel_top"]:getChildByName( "name_"..i ):setString( typeName ) -- 标签名字
		btn:setEnabled(true)
		btn:addClickEventListener(function()

			if i ~= self._curSelectedIndex then
				self._curSelectedIndex = i
				self:refreshSelectedTag()
			end
		end)
	end

	--显示幻化装备的内容 右下角panel
	self._ui["Panel/Panel_equip"]:setVisible( false )

	self._selectedClothes = NewClothesRender.create( self._ui["Panel/Panel_equip/icon"] ) -- 当前选中的时装

	self._selectedClothes:setClickEnable( false )

	self._previewFashionIDList = { 0, 0, 0, 0, 0 } -- 每一项显示预览的时装id列表
	self._isSelectedPreview = false --默认不显示预览

	self._shownChampionTime = self._ui["Panel/Panel_equip/champion_time"]
	self._shownPreviewText = self._ui["Panel/Panel_equip/Text_tick"]
	self._shownPreviewBtn = self._ui["Panel/Panel_equip/Button_tick"]
	self._shownPreviewBtn:setBright(not self._isSelectedPreview)
	self._shownPreviewBtn:addClickEventListener(function()
		local data = {}
		self._isSelectedPreview = not self._isSelectedPreview
		if self._isSelectedPreview then
			self:replacePreviewFashionId()
			--self._previewFashionIDList[self._curSelectedIndex] = tonumber( self._curSelectedClothesList[self._curSelectedIndex])
		else
			self._previewFashionIDList[self._curSelectedIndex] = 0
		end

		for k,v in ipairs(self._previewFashionIDList) do
			if v ~= 0 then
				local pos = tonumber(GD:getClothesConfig(v).location)
				data[pos] = v
			end
		end

		executeFunc( self._onPanelHandler, "ClothesPanel_previewClothes", data )
		self._shownPreviewBtn:setBright( not self._isSelectedPreview )
	end)



	self._clothesName = self._ui["Panel/Panel_equip/name"]
	self._text_1 = self._ui["Panel/Panel_equip/Text_1"]
	self._text_2 = self._ui["Panel/Panel_equip/Text_2"]
	self._buttonUse = self._ui["Panel/Panel_equip/Button_use"]
	self._buttonUseName = self._ui["Panel/Panel_equip/Button_use/name"]
	self._buttonDown = self._ui["Panel/Panel_equip/Button_down"]

	self._buttonUse:addClickEventListener(function()
		local dataTemp = self._curSelectedClothesList[self._curSelectedIndex]
		if dataTemp > 0 then
			if UD:isClothesActive( dataTemp ) then
				local btnName = self._ui["Panel/Panel_equip/Button_use/name"]:getString()
				if btnName == L("fashion_tips_1") then --已幻化为当前的了 啥都不做

				elseif btnName == L("fashion_button_1") then
					executeFunc(self._onPanelHandler, "ClothesPanel_useClothes", dataTemp)
				end
			else
				--显示获取途径
				local resourceData = GD:getClothResourceById( dataTemp )
				if resourceData then
					app:sendMsg( "HandbookController", "openGotWayView", resourceData )
					--display.resourceGotoFeature({feature = resourceData[1], param = resourceData[3]})
				end
			end
		end
	end)

	self._buttonDown:addClickEventListener(function()
		local dataTemp = self._curSelectedClothesList[self._curSelectedIndex]
		if dataTemp > 0 and UD:isClothesActive(dataTemp) then
			executeFunc(self._onPanelHandler, 'ClothesPanel_downClothes', dataTemp)
		end
	end)

	-- init scrollView
	local params = {
		renderClass = NewClothesRender,
		isMultipleLayer = true,
		perNum = 5,
		paddingLeft = 5,
		paddingRight = 5,
		gapY = 4,
		cellEventProxy = function(eventName, itemData)
			executeFunc(self._onPanelHandler, "ClothesPanel_clickItem", itemData)
		end,
	}
	self._listview = ListViewVertical.new( self._ui["Panel/ScrollView"], params )

	self:refreshSelectedTag()
end

function ClassRef:initSelectedRenderListData( idx, fashionId )
	self._curSelectedClothesList[idx] = fashionId
end

function ClassRef:resetPreviewData(pos)
	if pos then
		for i = 1, Top_OpItemNum do
			local  location = tonumber(GD:getClothesSubLocationFromID( i ))
			if pos == location then
				self._previewFashionIDList[i] = 0
				break
			end
		end

	else
		self._previewFashionIDList = { 0, 0, 0, 0, 0 } -- 每一项显示预览的时装id列表
	end
	self._isSelectedPreview = false
	self._shownPreviewBtn:setBright( true )
end

function ClassRef:refreshSelectedTag()
	self:refreshPanelTop()
	if self._onPanelHandler then
		executeFunc(self._onPanelHandler, "ClothesPanel_changeTag", self._curSelectedIndex)
	end
end

function ClassRef:refreshPanelTop()
	for i = 1, Top_OpItemNum do
		self._ui["Panel/Panel_top"]:getChildByName( "Button_"..i ):setBright( true )
		self._ui["Panel/Panel_top"]:getChildByName( "name_"..i ):setOpacity( 255 * 0.45 ) -- 45%透明度
	end
	self._ui["Panel/Panel_top"]:getChildByName( "Button_"..self._curSelectedIndex ):setBright( false )
	self._ui["Panel/Panel_top"]:getChildByName( "name_"..self._curSelectedIndex ):setOpacity( 255 )
end


function ClassRef:refreshPanelEquip()
	local curSelectedClothesData = self._curSelectedClothesList[self._curSelectedIndex]
	if not curSelectedClothesData or curSelectedClothesData == 0 then
		self._ui["Panel/Panel_equip"]:setVisible( false )
	else
		self._ui["Panel/Panel_equip"]:setVisible( true )

		self._selectedClothes:setData( curSelectedClothesData )
		self._selectedClothes:setIsNewShown( false )
		self._selectedClothes:setClickEnable( false )
		self._selectedClothes:setMaskShown(false)

		self._shownPreviewBtn:setBright( not self._isSelectedPreview )

		local flag =  false -- 是否幻化中？
		local conf = GD:getClothesConfig( curSelectedClothesData )
		local equipGrid =  UD:getEquipGridByPos( tonumber( conf.location ) ) -- 对应位置的装备
		if equipGrid then -- 格子数据
			if equipGrid:getFashionId() == curSelectedClothesData then -- 有幻化信息、且幻化的时装id = 当前选中
				flag = true
			end
		end
		local spRewardClothes = UD:getSpRewardClothesById(curSelectedClothesData)
		if spRewardClothes and spRewardClothes:getDuration() > 0 then
			self._shownChampionTime:setVisible(true)
            local str = ""
			local params = TimeUtil.secondsToStr(spRewardClothes:getDuration() - app.session:getServerTime(),4)
            if not params then
                str = L("countdowen_max")
            else
                if params[1] then
                    str = str..string.format(L("countdowen_day"), params[1])
                end
                if params[2] then
                    str = str..string.format(L("countdowen_hour"), params[2])
                end
                if params[3] then
                    str = str..string.format(L("countdowen_min"), params[3])
                end
            end
            self._shownChampionTime:setString(str)
		else
			self._shownChampionTime:setVisible(false)
		end


		self._buttonUse:setColor( display.COLOR_WHITE )
		if flag then
			self._buttonUse:setVisible(false)
			self._buttonDown:setVisible(true)
		else
			self._buttonUse:setVisible(true)
			self._buttonDown:setVisible(false)
			if UD:isClothesActive(curSelectedClothesData) then
				self._buttonUseName:setString( L("fashion_button_1") )
			else
				self._buttonUseName:setString( L("fashion_button_2") )
			end
		end

		self._clothesName:setString( L(conf.name) )
		local quality = tonumber(conf.quality)
		if quality >= 1 and quality <= #Enums.QualityColor then
			self._clothesName:setTextColor(Enums.QualityColor[quality])
		end

		self._text_2:setString( L(conf.getResource) )
		self._text_2:getVirtualRenderer():setDimensions( 300, 0 )
		local size = self._text_2:getVirtualRendererSize()
		self._text_2:setContentSize(300,size.height)

		local typeName = GD:getEquipPosName( tonumber( conf.location ) )
		self._text_1:setString(string.format(L("fashion_useDesc"),typeName))
	end
end

function ClassRef:setCurClothesRenderData( idx, fashionId )
	--把旧的取消选择
	-- print("================setCurClothesRenderData=====   ", idx, fashionId)
	-- local allRenders = self._listview:getAllRenders()
	-- for k,v in ipairs(allRenders) do
	-- 	if v:getData() ~= fashionId then
	-- 		v:setSelected(false)
	-- 	else
	-- 		v:setSelected(true)
	-- 	end
	-- end

	-- 默认选择 第一个
	if fashionId == 0 then
		fashionId = self._listview:getDataByIndex(1)
	end

	self._listview:foreachCellModels(function(model, renderData)
		if renderData then
			local trueOrFalse = fashionId == renderData
			if model.cell then
				model.cell:setSelected(trueOrFalse)
			else
				model:setUIState("selected", trueOrFalse)
			end
		end
	end)

	self._curSelectedClothesList[idx] = fashionId
	-- 选中时装时，如果已经幻化到当前人物身上装备时，需要选中身上时装
	local location = GD:getClothesSubLocationFromID( self._curSelectedIndex )
	local equipGrid = UD:getEquipGridByPos( location )
	if equipGrid and equipGrid:getFashionId() > 0 and equipGrid:getFashionId() == fashionId then
		--准备选中身上的装备
		executeFunc(self._onPanelHandler, "ClothesPanel_selectedClothesFromClothesPanel", location)
		--需要隐藏预览按钮以及显示预览的文字
		self._shownPreviewBtn:setVisible(false)
		self._shownPreviewText:setVisible(false)
	else
		self._shownPreviewBtn:setVisible(true)
		self._shownPreviewText:setVisible(true)
	end
	--根据现在预览值 让玩家换上预览装备
	if self._isSelectedPreview then
		self:replacePreviewFashionId()
		--self._previewFashionIDList[self._curSelectedIndex] = tonumber( self._curSelectedClothesList[self._curSelectedIndex])
		local data = {}

		for k,v in ipairs(self._previewFashionIDList) do
			if v ~= 0 then
				local pos = tonumber(GD:getClothesConfig(v).location)
				data[pos] = v
			end
		end

		executeFunc( self._onPanelHandler, "ClothesPanel_previewClothes", data )
	end
	self:refreshPanelEquip()
end

function ClassRef:refreshRedPoint()
	for i=1,Top_OpItemNum do
		local isRedPoint = UD.redPoint:getStateByKey(RedPointConstant["Clothes_" .. i])
		self._ui["Panel/Panel_top/dotNew_"..i]:setVisible( isRedPoint )
	end
end

function ClassRef:getCurClothesRenderDataByIdx( idx )
	return self._curSelectedClothesList[idx]
end

--获得当前选中页签的选中render
function ClassRef:getCurClothesRenderData()
	return self._curSelectedClothesList[self._curSelectedIndex]
end

function ClassRef:setCurSelectedIndex( index )
	self._curSelectedIndex = index
	self:refreshSelectedTag()
end

function ClassRef:registerOnOperate( cb )
	self._onPanelHandler = cb
end

function ClassRef:getScrollView()
	return self._listview
end

function ClassRef:remove()
	
end

function ClassRef:replacePreviewFashionId()
	local replaceId = tonumber( self._curSelectedClothesList[self._curSelectedIndex])
	for i, v in ipairs(self._previewFashionIDList) do
		local conf = GD:getFashionConf(replaceId)
		if not conf then return end

		local part1 = conf.part1
		for i,id in ipairs(self._previewFashionIDList) do
			conf = GD:getFashionConf(id)
			if conf and conf.part1 == part1 then
				self._previewFashionIDList[i] = 0
			end
		end
	end
	self._previewFashionIDList[self._curSelectedIndex] = replaceId
end

return ClassRef
